#!/bin/bash
{
	#////////////////////////////////////
	# DietPi Function: Change the system hostname
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Location: /boot/dietpi/func/change_hostname
	# - Usage: /boot/dietpi/func/change_hostname <hostname>
	#////////////////////////////////////

	# Import DietPi-Globals --------------------------------------------------------------
	. /boot/dietpi/func/dietpi-globals
	readonly G_PROGRAM_NAME='DietPi-Change_hostname'
	G_CHECK_ROOT_USER
	G_CHECK_ROOTFS_RW
	G_INIT
	# Import DietPi-Globals --------------------------------------------------------------

	# Set hostname if valid: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames
	if [[ $* =~ ^[[:alnum:]][[:alnum:].-]*[[:alnum:]]$ ]]
	then
		EXIT_CODE=0
		G_CONFIG_INJECT '127.0.1.1[[:blank:]]' "127.0.1.1 $*" /etc/hosts || EXIT_CODE=1
		echo "$*" > /etc/hostname || EXIT_CODE=1
		G_EXEC_NOEXIT=1 G_EXEC hostname "$*" || EXIT_CODE=1
	else
		EXIT_CODE=1
		G_DIETPI-NOTIFY 1 "Invalid hostname input ($*). Aborting..."
		G_DIETPI-NOTIFY 0 'Further info: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames'
	fi

	#-----------------------------------------------------------------------------------
	exit $EXIT_CODE
	#-----------------------------------------------------------------------------------
}
